//
//  AliCloudUpdate.m
//  GoodHabit
//
//  Created by 好习惯 on 16/7/11.
//  Copyright © 2016年 GoodHabit. All rights reserved.
//

#import "AliCloudUpdate.h"



@implementation AliCloudUpdate
- (void)initALi
{
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:@"Q0JwhJ1vl1wkibr8" secretKey:@"f9P4JqfSRRuvsGiyBKMYB1CsIuWy89"];
    
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    
    // 网络请求遇到异常失败后的重试次数
    conf.maxRetryCount = 3;
    
    // 网络请求的超时时间
    conf.timeoutIntervalForRequest =30;
    
    // 允许资源传输的最长时间
    conf.timeoutIntervalForResource =24 * 60 * 60;
    
    // 你的阿里地址前面通常是这种格式 ：http://oss……
    _client = [[OSSClient alloc] initWithEndpoint:@"http://oss-cn-hangzhou.aliyuncs.com/" credentialProvider:credential];
    
    
}
//5. 在 ImagePicker 方法中
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    [self performSelector:@selector(saveImage:) withObject:img afterDelay:0.1];
}
- (void)saveImage:(UIImage *)image {
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    // 图片名
    NSString *imageName = [NSString stringWithFormat:@"%@.jpg", [[NSUUID UUID] UUIDString]];

    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", imageName]];
        success = [fileManager fileExistsAtPath:imageFilePath];
        if(success) {
            [fileManager removeItemAtPath:imageFilePath error:&error];
        }
    
        UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(93,93)];
    
        [UIImageJPEGRepresentation(smallImage,0.3)writeToFile:imageFilePath atomically:YES];
        UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
    
    
        NSData *ImageData =UIImagePNGRepresentation(selfPhoto);
        [self updateToALi:ImageData imageName:imageName];

}
// 改变图片尺寸
-(UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    
    UIImage *newimage;
    
    if (nil == image) {
        
        newimage = nil;
        
    }
    
    else{
        
        CGSize oldsize = image.size;
        
        CGRect rect;
        
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            
            rect.size.height = asize.height;
            
            rect.origin.x = (asize.width - rect.size.width)/2;
            
            rect.origin.y =0;
            
        }
        
        else{
            
            rect.size.width = asize.width;
            
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            
            rect.origin.x =0;
            
            rect.origin.y = (asize.height - rect.size.height)/2;
            
        }
        
        UIGraphicsBeginImageContext(asize);
        
        CGContextRef context =UIGraphicsGetCurrentContext();
        
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        
        UIRectFill(CGRectMake(0,0, asize.width, asize.height));//clear background
        
        [image drawInRect:rect];
        
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
    }
    
    return newimage;
    
}


//5. 上传图片
- (void)updateToALi:(NSData *)data imageName:(NSString *)imageName
{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    
    put.bucketName =@"hahabit0328";
    put.objectKey = imageName;
    
    put.uploadingData = data; // 直接上传NSData
    //    put.uploadingFileURL = [NSURL fileURLWithPath:@"Users/haoxiguan/Library/Developer/CoreSimulator/Devices/9FB4A81C-A379-4C7B-8A56-F6751F11437A/data/Containers/Data/Application/40FE2A80-93B6-405A-84CF-7C969B52C215/Documents/currentImage.png"];
    
    
    put.uploadProgress = ^(int64_t bytesSent,int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    //     OSSTask * task = [_client getObject:get];
    
    OSSTask * putTask = [_client putObject:put];
    
    // 上传阿里云
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"upload object success!");
            
        } else {
            
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
    
}


- (void)updateToALi:(NSData *)data imageName:(NSString *)imageName completionBlock:(void (^)())completionblock
{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    
    put.bucketName =@"hahabit0328";
    put.objectKey = imageName;
    
    put.uploadingData = data; // 直接上传NSData
//    put.uploadingFileURL = [NSURL fileURLWithPath:@"Users/haoxiguan/Library/Developer/CoreSimulator/Devices/9FB4A81C-A379-4C7B-8A56-F6751F11437A/data/Containers/Data/Application/40FE2A80-93B6-405A-84CF-7C969B52C215/Documents/currentImage.png"];

    
    put.uploadProgress = ^(int64_t bytesSent,int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
//     OSSTask * task = [_client getObject:get];
    
    OSSTask * putTask = [_client putObject:put];
    
    // 上传阿里云
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
             NSLog(@"upload object success!");
             completionblock();
        } else {
            
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
    
}

@end
